package com.ljl.ningwei.controller;

import com.ljl.ningwei.domain.*;
import com.ljl.ningwei.entity.Category;
import com.ljl.ningwei.entity.Material;
import com.ljl.ningwei.common.page.PageInfoByApp;
import com.ljl.ningwei.common.result.Result;
import com.ljl.ningwei.service.CategoryService;
import com.ljl.ningwei.service.FileService;
import com.ljl.ningwei.service.MaterialService;
import com.ljl.ningwei.common.utils.ImagesUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 吕佳乐
 * @version 1.0
 * @date 2025-03-13 20:39
 */
@RestController
@RequiredArgsConstructor
@Slf4j
@Validated
public class MaterialController {

    private final MaterialService materialService;

    private final CategoryService categoryService;

    private final FileService fileService;

    /**
     * 首页物料分页查询
     *
     * @return
     */
    @RequestMapping("/material/list")
    public Result<PageVO> getMaterialList(@RequestParam(name = "wp", required = false) String wp,
                                          @RequestParam(name = "keyword", required = false) String keyword) {
        PageInfoByApp<Material> pageInfo;
        Map<Long, String> categoryMap;
        try {
            Wp wpobject = new Wp(wp);
            pageInfo = materialService.getMaterialListByApp(wpobject.getPageNum(), wpobject.getPageSize(), keyword);
            List<Category> categoryList = new ArrayList<>();
            // 列表不为空
            if (!CollectionUtils.isEmpty(pageInfo.getList())) {
                // 查询出分类总和
                categoryList = categoryService.listByIds(pageInfo.getList().stream()
                        .map(Material::getCategoryId)
                        .distinct()
                        .map(String::valueOf)
                        .collect(Collectors.joining(",")));
            }
            categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, Category::getName));
            List<MaterialFrontVO> materialFrontVOList = pageInfo.getList()
                    .stream()
                    .map(material -> {
                        MaterialFrontVO materialVO = new MaterialFrontVO()
                                .setMaterialId(material.getId())
                                .setName(material.getName())
                                .setCategoryName(categoryMap.get(material.getCategoryId()));
                        // 前置校验：确保 imageUrls 不为空且包含至少一个 URL
                        String[] urls = ImagesUtils.getUrl(material.getImageUrls());
                        // 获取到vo
                        String url = urls.length > 0 ? urls[0] : "";
                        Double imageAr = fileService.getImageAr(url);
                        ImageVO imageVO = new ImageVO()
                                .setImageUrl(url)
                                .setAr(imageAr);
                        materialVO.setImage(imageVO);
                        return materialVO;
                    })
                    .collect(Collectors.toList());
            PageVO pageVO = new PageVO()
                    .setList(materialFrontVOList)
                    .setIsEnd(pageInfo.getIsEnd())
                    .setWp(wpobject.getWp(wpobject.getPageNum() + 1, wpobject.getPageSize()));
            return Result.success(pageVO);
        } catch (Exception e) {
            log.info("异常为:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 根据分类ID进行查询
     *
     * @param wp
     * @param cid
     * @return
     */
    @RequestMapping("/material/listbycid")
    public Result<PageVO> getMaterialListByCid(@RequestParam(name = "wp", required = false) String wp,
                                               @RequestParam(name = "cid") Integer cid) {
        PageInfoByApp<Material> pageInfo;
        try {
            Wp wpobject = new Wp(wp);
            pageInfo = materialService.getMaterialListByAppAndCid(wpobject.getPageNum(), wpobject.getPageSize(), cid);
            List<MaterialListByCidVO> materialListByCidVOList = pageInfo.getList()
                    .stream()
                    .map(material -> {
                        MaterialListByCidVO materialVO = new MaterialListByCidVO()
                                .setMaterialId(material.getId())
                                .setName(material.getName());
                        // 前置校验：确保 imageUrls 不为空且包含至少一个 URL
                        String[] urls = ImagesUtils.getUrl(material.getImageUrls());
                        // 获取到vo
                        String url = urls.length > 0 ? urls[0] : "";
                        Double imageAr = fileService.getImageAr(url);
                        ImageVO imageVO = new ImageVO()
                                .setImageUrl(url)
                                .setAr(imageAr);
                        materialVO.setImageVO(imageVO);
                        return materialVO;
                    })
                    .collect(Collectors.toList());
            PageVO pageVO = new PageVO()
                    .setList(materialListByCidVOList)
                    .setIsEnd(pageInfo.getIsEnd())
                    .setWp(wpobject.getWp(wpobject.getPageNum() + 1, wpobject.getPageSize()));
            return Result.success(pageVO);
        } catch (Exception e) {
            log.info("异常为:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }


    @RequestMapping("/material/info")
    public Result<MaterialInfoVO> getMaterialInfo(@RequestParam(name = "id") Long id) {
        Material material = null;
        Category category = null;
        try {
            material = materialService.getById(id);
            category = categoryService.getById(material.getCategoryId());
        } catch (Exception e) {
            log.info("异常信息为:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

        MaterialInfoVO materialInfoVO = new MaterialInfoVO()
                .setMaterialName(material.getName())
                .setCategoryName(category.getName())
                .setProductName(material.getProductName())
                .setMaterialCount(material.getMaterialCount())
                .setImageUrls(ImagesUtils.getUrl(material.getImageUrls()))
                .setCategoryImageUrl(category.getImageUrl());

        return Result.success(materialInfoVO);
    }

}
